<?php

class SessionFilter extends CFilter {

    protected function preFilter($filterChain)
    {
        $action = Yii::app()->controller->id;
        if($action != 'login'){
            // check session user
            if(Yii::app()->user->isGuest){
                //check ajax request
                if(!Yii::app()->request->isAjaxRequest){
                    Yii::app()->request->redirect(Yii::app()->createUrl("login"));
                }else{
                    echo CJSON::encode(array("resultCd" => "02", "msg" => ""));
                }
                return false;
            }else{
                // get users information
                if(!isset(Yii::app()->session['userInfo'])){
                    $row = Yii::app()->db->createCommand(array(
                        'select' => 'FN_ZZ_MULTI_NAME(A.USER_NAME,A.USER_ENG_NAME,:LANG_CODE) AS USER_NAME, A.FORMAT_DATE, A.FORMAT_TIME, A.LANGUAGE, C.URL',
                        'from' => 'TBL_USERS A',
                        'where' => 'USER_ID = :USER_ID',
                        'params' => array(':USER_ID'=>Yii::app()->user->getId(), ':LANG_CODE' => Yii::app()->language),
                    ))->leftJoin("TBL_FILE_ATTACH_GRP B","A.AVATAR = B.FILE_ATTACH_NO")
                        ->leftJoin("TBL_FILE_ATTACH C","B.FILE_ATTACH_NO = C.FILE_ATTACH_NO AND C.FILE_DETAIL_CODE = AVATAR")
                        -> queryRow();
                    Yii::app()->session['userInfo'] = CJSON::encode($row);
                }
            }

        }else{
            //check session
            if(!Yii::app()->user->isGuest){
                //check ajax request
                if(!Yii::app()->request->isAjaxRequest){
                    Yii::app()->request->redirect(Yii::app()->createUrl("site"));
                }else{
                    echo CJSON::encode(array("resultCd" => "02", "msg" => ""));
                }
                return false;
            }

        }


        return true; // TODO: Change the autogenerated stub
    }

    protected function postFilter($filterChain)
    {
        parent::postFilter($filterChain); // TODO: Change the autogenerated stub
    }

} 